package com.shoppingmall.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shoppingmall.bean.UserLoginBean;
import com.shoppingmall.service.LoginService;

/**
 * 登陆处理器
 * @author LIU
 * @version 1.0 2017-11-8
 */
@Controller
public class LoginController {

	@Autowired
	LoginService loginService;
	
	
	/**
	 * 跳转登陆页面
	 *TODO
	 *LIU
	 * @return String
	 *下午8:31:40
	 */
	@RequestMapping("loginView")
	public String loginView(Model model, HttpServletRequest request) {
		//拿到客户端的cookie
		Cookie[] cookies = request.getCookies();
		//循环找到相应的cookie
		for (Cookie cookie : cookies) {
			if(null != cookie.getName() && cookie.getName().equals("usernameAndpassword")) {
				String val = cookie.getValue();
				// 根据存进去的方式解析出来
				String [] user = val.split(":");
				UserLoginBean userLogin = new UserLoginBean(user[0],user[1]);
				System.out.println("Cookie里面的用户：" + userLogin);
				model.addAttribute("userLogin",userLogin);
			};
		}
		System.out.println("跳转login.jsp页面...");
		return "login";
	}
	
	
	
	
	
	
	/**
	 * 验证用户登陆
	 *TODO
	 *LIU
	 * @return String
	 *下午11:07:54
	 */
	@RequestMapping("verifyLogin")
	public String verifyLogin(UserLoginBean userLogin, Model model, HttpServletRequest request, HttpServletResponse response) {
		System.out.println("验证用户名和密码:" + userLogin.toString());
		if(null != request.getSession().getAttribute("username") && request.getSession().getAttribute("username").equals(userLogin.getUsername())) {
			model.addAttribute("error","该用户已经登录！！");
			return "login";
		}
		
		boolean result = false;
		if(userLogin != null && !userLogin.getUsername().equals("") && !userLogin.getPassword().equals("")) {
			result = loginService.getUserLoginCount(userLogin);	
		}
		model.addAttribute("userLogin",userLogin);
		if(result) {
			//存在这个用户  才记住密码
			if(request.getParameter("chkRememberMe") != null) {
				//new一个cookie，用于存用户名和密码
				Cookie c = new Cookie("usernameAndpassword",userLogin.getUsername() +":"+ userLogin.getPassword());
				//最大的声明周期   以秒为单位
				c.setMaxAge(60*60*24*7);
				//推送到客户端
				response.addCookie(c);
			}else {
				//new一个cookie
				Cookie c = new Cookie("usernameAndpassword",userLogin.getUsername() +":"+ userLogin.getPassword());
				//最大的声明周期   以秒为单位
				c.setMaxAge(0);
				//推送到客户端
				response.addCookie(c);
			}
			request.getSession().setAttribute("username", userLogin.getUsername());
			return "index";
		}else {
			model.addAttribute("error","用户名或密码填写不正确！！");
			return "login";
		}
	}
	
	
	
	
	/**
	 * 注销登陆
	 * @param request
	 * @return String
	 */
	@RequestMapping("outLogin")
	public String outLogin(HttpServletRequest request) {
		request.getSession().removeAttribute("username");
		return "login";
	}
	
	
}
